package demo.view;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import demo.controler.AddressBookControler;
import demo.model.AddressBook;
import demo.model.Contact;
import demo.model.ContactObserver;

public class ContactView extends JPanel implements ContactObserver {
	private static final long serialVersionUID = 1L;

	JLabel lastName, firstName, phoneNumber;
	Contact currentContact;

	public ContactView(final AddressBookControler ctrl) {
		super(new GridLayout(7, 1));

		JPanel pane = new JPanel();
		JButton btnEdit = new JButton("Edit");
		JButton btnCreate = new JButton("Create");

		add(LabelFactory.createHeader("Last Name"));
		add(lastName = new JLabel());
		add(LabelFactory.createHeader("First Name"));
		add(firstName = new JLabel());
		add(LabelFactory.createHeader("Phone number"));
		add(phoneNumber = new JLabel());
		btnCreate.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ContactEdit editor = ContactEdit.getCreateWindows(ctrl);
				editor.setVisible(true);
			}
		});
		btnEdit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (currentContact != null) {
					ContactEdit editor = ContactEdit
							.getWindowsFor(ctrl, currentContact);
					editor.setVisible(true);
				}
			}
		});

		pane.add(btnCreate);
		pane.add(btnEdit);
		add(pane);

		ctrl.addObserver(this);
	}

	public void bindToContact(Contact contact) {
		if (currentContact != contact) {
			currentContact = contact;
			refresh();
		}
	}

	@Override
	public void updateContact(Contact contact, AddressBook addressBook) {
		if (contact == currentContact) {
			refresh();
		}
	}

	private void refresh() {
		Contact contact = currentContact;
		lastName.setText(contact == null ? "" : contact.getLastName());
		firstName.setText(contact == null ? "" : contact.getFirstName());
		phoneNumber.setText(contact == null ? "" : contact.getPhoneNumber());
	}
}
